package com.zzx.entity;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.zzx.common.constant.HttpStatus;
import lombok.Builder;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;

import java.io.Serializable;
import java.util.Date;

@Data
@Builder
public class ApiResult implements Serializable {

    private static final String SUCCESS_MSG = "成功";
    private static final String FAILED_MSG = "失败";
    private static final String OPERATION_SUCCESS = "操作成功";
    private static final String OPERATION_FAILED = "操作失败";

    /**
     * 响应码
     */
    private String status;

    /**
     * 响应消息
     */
    private String msg;

    /**
     * 响应数据
     */
    private Object data;

    /**
     * 响应时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date time;

    /**
     * 根据条件判断，返回操作结果
     */
    public static ApiResult result(Boolean flag, String msgPrefix) {
        if (flag) {
            return ok(msgPrefix + SUCCESS_MSG);
        }
        return failed(msgPrefix + FAILED_MSG);
    }

    /**
     * 操作成功
     */
    public static ApiResult ok() {
        return ok(null);
    }

    /**
     * 操作成功
     */
    public static ApiResult ok(String msg) {
        return ok(msg, null);
    }

    /**
     * 操作成功
     */
    public static ApiResult ok(Object data) {
        return ok(null, data);
    }

    /**
     * 操作成功
     */
    public static ApiResult ok(String msg, Object data) {
        if (msg == null) {
            msg = OPERATION_SUCCESS;
        }
        return ApiResult.builder()
                .status(String.valueOf(HttpStatus.SUCCESS))
                .msg(msg)
                .data(data)
                .time(new Date())
                .build();
    }

    /**
     * 操作失败
     */
    public static ApiResult failed() {
        return failed(null);
    }

    /**
     * 操作失败
     */
    public static ApiResult failed(String msg) {
        return failed(msg, null);
    }

    /**
     * 操作失败
     */
    public static ApiResult failed(Object data) {
        return failed(null, data);
    }

    /**
     * 操作失败
     */
    public static ApiResult failed(String msg, Object data) {
        if (msg == null) {
            msg = OPERATION_FAILED;
        }
        return ApiResult.builder()
                .status(String.valueOf(HttpStatus.ERROR))
                .msg(msg)
                .data(data)
                .time(new Date())
                .build();
    }
}
